package DBLayer;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import ModelLayer.Employee;
import ModelLayer.RegularDayOff;

public class DBRegularDayOff implements IFDBRegularDayOff
{
	private Connection con;
	
	public DBRegularDayOff()
	{
		con = DBConnection.getInstance().getDBcon();
	}
	
	public RegularDayOff getRegDayOff(int empId, String dayOfWeek) 
	{
		return singleWhere("ID = DayOffID AND EmployeeId = " + empId + " AND DayOfWeek = '" + dayOfWeek + "'");
	}

	private RegularDayOff singleWhere(String wClause)
	{
		ResultSet result;
		
		RegularDayOff regDayOff = null;
		
		String query = buildQuery(wClause);
		
		try
		{
			Statement stmt = con.createStatement();
			stmt.setQueryTimeout(5);
			result = stmt.executeQuery(query);
			
			if(result.next())
			{
				regDayOff = buildRegularDayOff(result);
			}
			
			stmt.close();
		}
		catch(SQLException sqlEx)
		{
			sqlEx.printStackTrace();
		}
		
		return regDayOff;
	}
	
	private RegularDayOff buildRegularDayOff(ResultSet result)
	{
		RegularDayOff regDayOff = new RegularDayOff();
		
		try
		{
			regDayOff.setId(result.getInt("ID"));
			regDayOff.setType(result.getString("Type"));
			regDayOff.setEmployee(new Employee(result.getInt("EmployeeID")));
			regDayOff.setDayOfWeek(result.getString("DayOfWeek"));
		}
		catch(Exception err)
		{
			
		}
		
		return regDayOff;
	}
	
	private String buildQuery(String wClause)
	{
		String query = "SELECT ID, Type, EmployeeID, DayOfWeek FROM DayOff, RegularDayOff";
		
		if(wClause.length() > 0)
		{
			query = query + " WHERE " + wClause;
		}
		
		return query;
	}
}
